<template>
	<view class="main">
		<view>
			<u-text text="注册" size="20"></u-text>
		</view>
		<view style="margin-top: 10px;">
			<u-form :model="registerForm">
				<u-form-item>
					<u--input placeholder="请输入用户名" v-model="registerForm.username"></u--input>
				</u-form-item>

				<u-form-item>
					<u--input placeholder="请输入密码" v-model="registerForm.password" type="password"></u--input>
				</u-form-item>

				<u-form-item>
					<u--input placeholder="请确认密码" v-model="registerForm.confirmPassword" type="password"></u--input>
				</u-form-item>

				<u-form-item>
					<u-row>
						<u-col span="7">
							<u--input placeholder="请输入验证码" v-model="registerForm.code"></u--input>
						</u-col>
						<u-col span="3" offset="1">
							<u-image :src="codeUrl" mode="heightFix" height="38px" @click="getCode()"></u-image>
						</u-col>
					</u-row>
				</u-form-item>

				<view style="margin-top: 10px;">
					<u-button type="warning" @click="handleRegister()">注册</u-button>
				</view>

			</u-form>
		</view>
	</view>
</template>

<script>
	import {
		getCodeImg,
		register
	} from '@/api/user/register.js'
	export default {
		data() {
			return {
				codeUrl: "",
				registerForm: {
					username: "",
					password: "",
					confirmPassword: "",
					code: "",
					uuid: ""
				},
			}
		},
		methods: {
			getCode() {
				getCodeImg().then(res => {
					this.codeUrl = "data:image/gif;base64," + res.img;
					this.registerForm.uuid = res.uuid;
				})
			},
			handleRegister() {
				if (this.registerForm.password !== this.registerForm.confirmPassword) {
					uni.showModal({
						title: '提示',
						content: '前后密码不一致',
						showCancel: false
					})
				} else {
					register(this.registerForm).then(res => {
						if (res.code == 200) {
							uni.showToast({
								title: '注册成功',
								icon: 'success'
							})
							setTimeout(
								function() {
									uni.redirectTo({
										url: '/pages/login/index'
									})
								}, 2000)
						} else {
							this.getCode()
							uni.showModal({
								title: '提示',
								content: res.msg,
								showCancel: false
							})
						}
					})
				}
			},
			onLoad(options) {
				this.getCode();
			}
		}
	}
</script>

<style>
	.main {
		margin: 10px 10px 10px 10px;
	}
</style>
